using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using BBX.Common;
using BBX.Config;
using BBX.Entity;
using BBX.Forum;

namespace BBX.Web.UI
{
    public class TopicPage : PageBase
    {
        public Topic topic;
        public Int32 forumid = DNTRequest.GetInt("forumid", 0);
        public Int32 topicid = DNTRequest.GetInt("topicid", -1);
        public Boolean needlogin;
        public IXForum forum = new XForum();
        public Boolean canreply;
        public Int32 ismoder;
        protected String msg = "";
        public Boolean canposttopic;
        public Boolean isenddebate;
        public List<Attachment> attachmentlist;
        public String doublead = "";
        public String floatad = "";
        public String[] quickbgad;
        public Int32 pageid;
        public Int32 postcount;
        public Int32 pagecount;
        public String pagenumbers = "";
        public Int32 topicviews;
        public String[] pagewordad = new String[0];
        public Boolean allowvote;
        public Int32 parseurloff = DNTRequest.GetString("parseurloff").ToInt(0);
        public Int32 smileyoff;
        public Int32 bbcodeoff = 1;
        public Int32 usesig = (ForumUtils.GetCookie("sigstatus") == "0") ? 0 : 1;
        public String voters = "";
        public Boolean disablepostctrl;
        public AdminGroup admininfo;
        public String onlyauthor = DNTRequest.GetString("onlyauthor");
        public String topictypes = "";
        public TopicIdentify topicidentify;
        public String[] score = new String[0];
        public String[] scoreunit = new String[0];
        public String inpostad = "";
        public String quickeditorad = "";
        public List<Topic> relatedtopics = new List<Topic>();
        public Int32 ppp = ForumUtils.GetCookie("ppp").ToInt(GeneralConfigInfo.Current.Ppp);
        public Boolean enabletag;
        public String postleaderboardad = "";
        public Int32 replynotificationstatus = GeneralConfigInfo.Current.Replynotificationstatus;
        public Int32 replyemailstatus = GeneralConfigInfo.Current.Replyemailstatus;
        public String downloadattachmenttip = "";
        public Boolean isnewbie;
        public Int32 postid = DNTRequest.GetInt("postid", 0);
        public Int32 forumpid = Utils.GetCookie("forumpageid").ToInt(1);

        protected Boolean ValidateInfo()
        {
            if (topicid == -1 || topic == null)
            {
                base.AddErrLine("无效或不存在的主题ID");
                return false;
            }
            if (topic.Closed > 1)
            {
                topicid = topic.Closed;
                //this.topic = Topics.GetTopicInfo(this.topicid);
                topic = Topic.FindByID(topicid);
                if (topic == null || topic.Closed > 1)
                {
                    base.AddErrLine("不存在的主题ID");
                    return false;
                }
            }
            if (topic.ReadPerm > usergroupinfo.Readaccess && topic.PosterID != userid && useradminid != 1 && ismoder != 1)
            {
                base.AddErrLine(string.Format("本主题阅读权限为: {0}, 您当前的身份 \"{1}\" 阅读权限不够", topic.ReadPerm, usergroupinfo.GroupTitle));
                if (userid == -1)
                {
                    needlogin = true;
                }
                return false;
            }
            if (topic.DisplayOrder == -1)
            {
                base.AddErrLine("此主题已被删除！");
                return false;
            }
            if (topic.DisplayOrder == -2 && topic.PosterID != userid)
            {
                base.AddErrLine("此主题未经审核！");
                return false;
            }
            return ValidateForumPassword() && ValidateAuthority();
        }

        public Boolean ValidateAuthority()
        {
            if (!UserAuthority.VisitAuthority(forum, usergroupinfo, userid, ref msg))
            {
                base.AddErrLine(msg);
                if (userid == -1)
                {
                    needlogin = true;
                }
                return false;
            }
            canreply = (ismoder == 1 || UserAuthority.PostReply(forum, userid, usergroupinfo, topic));
            if (userid > -1)
            {
                canposttopic = UserAuthority.PostAuthority(forum, usergroupinfo, userid, ref msg);
                if (!canposttopic && !pagename.StartsWith("showtopic") && !pagename.StartsWith("showtree"))
                {
                    base.AddErrLine(msg);
                    return false;
                }
            }
            if (useradminid != 1 && !usergroupinfo.DisablePeriodctrl)
            {
                var text = "";
                if (Scoresets.BetweenTime(config.Postbanperiods, out text))
                {
                    canposttopic = false;
                }
                isnewbie = UserAuthority.CheckNewbieSpan(userid);
            }
            return true;
        }

        public Boolean ValidateForumPassword()
        {
            if (!forum.Password.IsNullOrEmpty() && Utils.MD5(forum.Password) != ForumUtils.GetCookie("forum" + forumid + "password"))
            {
                base.AddErrLine("本版块被管理员设置了密码");
                if (config.Aspxrewrite == 1)
                {
                    HttpContext.Current.Response.Redirect(BaseConfigs.GetForumPath + "showforum-" + forumid + config.Extname, true);
                }
                else
                {
                    HttpContext.Current.Response.Redirect(BaseConfigs.GetForumPath + "showforum.aspx?forumid=" + forumid, true);
                }
                return false;
            }
            return true;
        }

        public void GetForumAds(Int32 forumid)
        {
            headerad = Advertisement.GetOneHeaderAd("", forumid);
            footerad = Advertisement.GetOneFooterAd("", forumid);
            pagewordad = Advertisement.GetPageWordAd("", forumid);
            doublead = Advertisement.GetDoubleAd("", forumid);
            floatad = Advertisement.GetFloatAd("", forumid);
            if (forumid > 0)
            {
                postleaderboardad = Advertisement.GetOnePostLeaderboardAD("", forumid);
            }
        }

        public void EditorState()
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("var Allowhtml=1;\r\n");
            smileyoff = forum.AllowSmilies ? 0 : 1;
            stringBuilder.Append("var Allowsmilies=" + (1 - smileyoff) + ";\r\n");
            if (forum.Allowbbcode == 1 && usergroupinfo.AllowCusbbCode)
            {
                bbcodeoff = 0;
            }
            stringBuilder.Append("var Allowbbcode=" + (1 - bbcodeoff) + ";\r\n");
            stringBuilder.Append("var Allowimgcode=" + forum.Allowimgcode + ";\r\n");
            base.AddScript(stringBuilder.ToString());
        }

        public void UpdateMetaInfo(String metadescritpion)
        {
            var seokeywords = config.Seokeywords;
            metadescritpion = ((metadescritpion.Length > 100) ? metadescritpion.Substring(0, 100) : metadescritpion);
            if (enabletag && Topics.GetMagicValue(topic.Magic, MagicType.TopicTag) == 1)
            {
                seokeywords = Tag.GetTagsByTopicId(topic.ID);
            }
            meta = PageHelper.UpdateMetaInfo(meta, seokeywords, metadescritpion, config.Seohead);
        }

        public Topic GetTopicInfo()
        {
            var mode = DNTRequest.GetString("go").Trim().ToLower();
            if (String.IsNullOrEmpty(mode))
            {
                forumid = 0;
            }
            else
            {
                if (forumid == 0) mode = "";
            }
            //string a;
            Topic topicInfo;

            if (mode == "prev")
                topicInfo = Topic.GetTopicInfo(topicid, forumid, 1);
            else if (mode == "next")
                topicInfo = Topic.GetTopicInfo(topicid, forumid, 2);
            else
                topicInfo = Topic.FindByID(topicid);

            if (topicInfo == null)
            {
                if (mode == "prev")
                {
                    msg = "没有更旧的主题, 请返回";
                }
                else
                {
                    if (mode == "next")
                    {
                        msg = "没有更新的主题, 请返回";
                    }
                    else
                    {
                        msg = "该主题不存在";
                    }
                }
                //if (DiscuzCloud.GetCloudServiceEnableStatus("connect"))
                //{
                //    DeleteFeed deleteFeed = new DeleteFeed();
                //    deleteFeed.DeleteTopicPushedFeed(this.topicid);
                //}
                base.AddErrLine(msg);
                GetForumAds(0);
            }
            return topicInfo;
        }

        public void GetPostAds(PostpramsInfo postpramsInfo, Int32 count)
        {
            inpostad = Advertisement.GetInPostAd("", forumid, templatepath, (count > postpramsInfo.Pagesize) ? postpramsInfo.Pagesize : count);
            quickeditorad = Advertisement.GetQuickEditorAD("", forumid);
            quickbgad = Advertisement.GetQuickEditorBgAd("", forumid);
            if (quickbgad.Length <= 1)
            {
                quickbgad = new String[]
                {
                    "",
                    ""
                };
            }
        }

        public void BindPageCountAndId()
        {
            ppp = ((ppp <= 0) ? config.Ppp : ppp);
            if (DNTRequest.GetInt("stand", 0) == 0)
            {
                postcount = Post.GetPostCountByPosterId(onlyauthor, topicid, topic.PosterID, topic.Replies);
            }
            else
            {
                postcount = Post.GetDebatePostCount(onlyauthor, topicid, topic.PosterID, DNTRequest.GetInt("stand", 0));
            }
            pagecount = ((postcount % ppp == 0) ? (postcount / ppp) : (postcount / ppp + 1));
            if (pagecount == 0)
            {
                pagecount = 1;
            }
            pageid = (DNTRequest.GetString("page").ToLower().Equals("end") ? pagecount : DNTRequest.GetInt("page", 1));
            if (postid > 0)
            {
                pageid = Post.GetPostCountBeforePid(postid, topicid) / ppp + 1;
            }
            pageid = ((pageid < 1) ? 1 : pageid);
            pageid = ((pageid > pagecount) ? pagecount : pageid);
        }

        public void IsModer()
        {
            if (useradminid != 0)
            {
                ismoder = Moderators.IsModer(useradminid, userid, forum.Fid) ? 1 : 0;
                admininfo = AdminGroup.FindByID(usergroupid);
                if (admininfo != null)
                {
                    disablepostctrl = admininfo.DisablePostctrl;
                }
            }
        }

        public void BindDownloadAttachmentTip()
        {
            if (!Scoresets.IsSetDownLoadAttachScore())
            {
                return;
            }
            var userExtCredits = Scoresets.GetUserExtCredits(CreditsOperationType.DownloadAttachment);
            var validScoreName = Scoresets.GetValidScoreName();
            var validScoreUnit = Scoresets.GetValidScoreUnit();
            for (var i = 0; i < userExtCredits.Length; i++)
            {
                if (userExtCredits[i] < 0f)
                {
                    downloadattachmenttip += string.Format("{0}:{1} {2};", validScoreName[i + 1], Math.Abs(userExtCredits[i]), validScoreUnit[i + 1]);
                }
            }
            downloadattachmenttip = downloadattachmenttip.TrimEnd(';');
        }
    }
}